package com.agile.leetcode.order.redis;

import com.agile.leetcode.redis.jedis.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.Calendar;
import java.util.Set;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/15 10:46
 */
public class RedisOrder {


    // 生产者,生成5个订单放进去
    public void productionDelayMessage() {
        for (int i = 0; i < 5; i++) {
            // 延迟三秒放
            Calendar calendar = Calendar.getInstance();
            // 加三秒
            calendar.add(Calendar.SECOND, 3);
            // 过期时间
            int second3later = (int) (calendar.getTimeInMillis() / 100);
            // 放入redis
            JedisUtil.getJedis().zadd("OrderId", second3later, "OID0000001" + i);
            System.out.println(System.currentTimeMillis() + "ms:redis生成了一个订单任务：订单ID为" + "OID0000001" + i);
        }
    }
    //消费者，取订单

    public void consumerDelayMessage() {
        Jedis jedis = JedisUtil.getJedis();
        while (true) {
            // 拿到第一个
            Set<Tuple> orderId = jedis.zrangeWithScores("OrderId", 0, 1);
            if (orderId == null || orderId.isEmpty()) {
                System.out.println("当前没有等待的任务");
                try {
                    // 休眠一会儿再取
                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }
            int score = (int) ((Tuple) orderId.toArray()[0]).getScore();
            // 拿到日期实例
            Calendar instance = Calendar.getInstance();
            int nowSecond = (int) (instance.getTimeInMillis() / 1000);
            if (nowSecond > score) {
                // 此时超时未消费
                // 拿到元素-<订单id
                String element = ((Tuple) orderId.toArray()[0]).getElement();
                // 移除 除users中的一个或多个成员，不存在的成员将被忽略。
                Long id = jedis.zrem("OrderId", element);
                // 防止高并发时多个消费者消费同一个orderId,当移除成功的线程才能消费
                if (id != null && id > 0) {
                    System.out.println(System.currentTimeMillis() + "ms:redis消费了一个任务：消费的订单OrderId为" + element);
                }
            }
        }
    }
}
